<template>
  <div class="ArticleManage-container">
    <div class="ArticleManage-options">
      <el-input
        placeholder="请输入内容"
        style="width:60%;"
        @change="SearchArticles"
        v-model="content"
      >
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <el-button type="primary" style="margin-left:20px" @click="publishArticle"
        >添加文章</el-button
      >
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
      <el-button
        style="margin-left:20px"
        type="warning"
        @click="OpenDeleteListDialog"
        >待删除列表</el-button
      >
    </div>
    <div class="ArticleManage-table" v-if="articleList.length">
      <el-table
        :data="articleList"
        border
        @selection-change="handleSelectionChange"
        max-height="80%"
        :default-sort="{ prop: 'date', order: 'descending' }"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="创建日期" sortable width="180">
          <template slot-scope="scope">
            <svg-icon icon-class="date"></svg-icon>
            <span style="margin-left: 10px">{{
              scope.row.create_time | formatDate
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标题">
          <template slot-scope="scope">
            <el-popover trigger="click" placement="top">
              <div class="tagList" v-if="tagList.length">
                所有标签:
                <el-tag type="info" v-for="t in tagList" :key="t.id">
                  {{ t.tag_name }}
                </el-tag>
              </div>
              <div class="tagList" v-else>
                暂无任何标签
              </div>
              <div slot="reference" class="name-wrapper">
                <el-tag @click="getArticleTags(scope.row.id)" size="medium">{{
                  scope.row.article_title
                }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="内容">
          <template slot-scope="scope">
            <span>{{ scope.row.article_abstract }}</span>
          </template>
        </el-table-column>
        <el-table-column label="封面">
          <template slot-scope="scope">
            <img :src="scope.row.img_url" style="width:150px" />
          </template>
        </el-table-column>
        <el-table-column label="喜欢数" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.like_count }}</span>
          </template>
        </el-table-column>
        <el-table-column label="评论数" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.comment_count }}</span>
          </template>
        </el-table-column>
        <el-table-column label="浏览数" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.view_count }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <!-- <el-button size="mini"
                     type="info"
                     @click="handleEdit(scope.$index, scope.row)">更改密码</el-button> -->
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :limit="limit"
        :page-size="limit"
        :current-page="page"
        small
        @current-change="pageChange"
        layout="prev, pager, next"
        :total="count"
      >
      </el-pagination>
    </div>
    <div v-else style="display:flex;justify-content:center">
      <img
        style="width:50%;margin:0 auto"
        src="@/assets/img/search-empty.png"
      />
    </div>
    <PublishDialog
      :data="EditForm"
      type="article"
      dialogTitle="编辑文章"
      :visible="EditDialogVisible"
      @custom-confirm="EditConfirm"
      @custom-close="EditDialogClose"
    />
    <PublishDialog
      :data="publishForm"
      dialogTitle="添加文章"
      type="article"
      :visible="PublishDialogVisible"
      @custom-confirm="PublishConfirm"
      @custom-close="PublishDialogClose"
    />
    <!-- 删除列表对话框 -->

    <DeleteListDialog
      :data="DeleteList"
      dialogTitle="删除文章列表"
      :pageSize="pageSize"
      :total="total"
      type="article"
      @custom-reload="getDeleteList"
      @current-page-change="DeleteListPageChange"
      :visible="DeleteListDialogVisible"
      @custom-close="DeleteListDialogClose"
    />
  </div>
</template>

<script>
import { encryptData } from '@/utils/encrypt'
import EditDialog from '@/components/Dialog/EditDialog'
import PublishDialog from '@/components/Dialog/PublishDialog'
import DeleteListDialog from '@/components/Dialog/DeleteListDialog'
export default {
  // 引入组件
  components: {
    EditDialog,
    PublishDialog,
    DeleteListDialog
  },
  data() {
    return {
      limit: 10,
      page: 1,
      // 权限数据
      tagList: [],
      isEdit: false,
      count: 0,
      // 文章列表
      articleList: [],
      content: '',
      // 编辑数据
      EditDialogVisible: false,
      formLabelWidth: '80px',
      // 编辑表单
      EditForm: {},
      // 添加表单
      publishForm: {
        title: '',
        content: ''
      },
      // 添加文章窗口显示标志位
      PublishDialogVisible: false,
      selectedArticles: '',
      DeleteListDialogVisible: false,
      DeleteList: [], // 已删除列表
      // 删除列表分页信息
      pageSize: 3,
      currentPage: 1,
      total: null
    }
  },
  created() {
    // 获取文章列表
    this.$nextTick(() => {
      this.getArticleList()
    })
  },
  methods: {
    // 关闭已删除列表回调
    DeleteListDialogClose() {
      // 重新获取文章列表
      this.getArticleList().then(() => {
        this.DeleteListDialogVisible = false
      })
    },
    // 打开待删除列表
    OpenDeleteListDialog() {
      this.getDeleteList()
        .then(() => {
          this.DeleteListDialogVisible = true
        })
        .catch(error => {
          console.log(error)
          this.$message.error('获取已删除列表失败')
        })
    },
    // 获取已删除列表
    async getDeleteList() {
      const { pageSize, currentPage } = this
      const res = await this.$API.article.getArticleDeleteList(
        pageSize,
        currentPage
      )
      // 如果未获取到数据就退回一页重新获取数据
      if (res && !res.data) {
        if (currentPage <= 1) {
          return (this.DeleteList = [])
        } else {
          this.currentPage--
          this.getDeleteList()
        }
      }
      if (res.status == 200) {
        this.DeleteList = res.data.payload
        this.total = res.data.count
      } else {
        return this.$message.error('获取以删除列表失败')
      }
    },
    // 已删除列表页数改变
    DeleteListPageChange(currentPage) {
      this.currentPage = currentPage
      // 重新获取列表
      this.getDeleteList()
    },
    // 获取文章列表
    async getArticleList() {
      const { limit, page } = this
      // 如果处于搜索状态就继续搜索
      if (this.content) {
        this.SearchArticles()
      }
      const res = await this.$API.article.getArticleList(limit, page)
      if (!res.data) this.articleList = []
      if (res.status == 200) {
        this.count = res.data.count
        this.articleList = res.data.payload
      }
    },
    // 页数改变
    pageChange(page) {
      console.log('page', page)
      this.page = page
      this.getArticleList()
    },
    // 添加文章确认功能回调
    async PublishConfirm(formData) {
      // 整理数据
      const datas = this.$qs.stringify(formData)
      const res = await this.$API.article.publishArticle(datas)
      if (res.status == 200) {
        this.$message.success('添加成功')
        // 初始化数据
        this.PublishDialogVisible = false
        this.content = ''
        this.getArticleList()
      }
    },
    // 添加文章窗口关闭回调
    PublishDialogClose() {
      this.PublishDialogVisible = false
    },
    // 编辑文章
    async handleEdit(id, article) {
      console.log(article)
      // 获取文章详情内容
      const res = await this.$API.article.RefreshArticle(article.id)
      if (res.status == 200) {
        // 整理数据
        let datas = {
          article_id: article.id,
          title: article.article_title,
          content: res.data.content,
          img_url: article.img_url
        }
        // 获取数据
        this.EditForm = datas
        this.EditDialogVisible = true
      } else {
        this.$messager.error('该文章不存在')
      }
    },
    // 删除文章
    handleDelete(id, article) {
      this.$confirm('此操作将删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const datas = new FormData()
          datas.append('article_id', article.id)
          const res = await this.$API.article.deleteArticle(datas)
          if (res.status == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 初始化数据
            this.getArticleList()
            this.content = ''
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 搜索文章
    async SearchArticles() {
      this.page = 1
      const { content, page, limit } = this
      console.log(content, page, limit)
      // 如果不存在搜索内容就获取全部
      if (!this.content) return this.getArticleList()
      const res = await this.$API.article.SearchArticles(content, limit, page)
      // 如果不存在文章就显示空
      if (!res.data) this.articleList = []
      console.log(res)
      if (res.status == 200) {
        this.articleList = res.data.payload
        this.count = res.data.count
      }
    },
    // 关闭对话框
    EditDialogClose() {
      this.EditDialogVisible = false
    },
    // 确定编辑
    async EditConfirm(formData) {
      // 整理数据
      let { id } = formData
      const datas = {
        ...formData
      }
      const res = await this.$API.article.EditArticle(this.$qs.stringify(datas))
      if (res.status == 200) {
        this.$message.success('编辑成功')
        // 初始化数据
        this.EditDialogVisible = false
        this.content = ''

        this.getArticleList()
        this.EditForm = {}
      } else {
        this.$message.error('编辑失败')
      }
    },
    // 添加文章
    publishArticle() {
      this.publishForm = {
        title: '',
        content: ''
      }
      this.PublishDialogVisible = true
    },
    // 通过文章id获取用户的权限
    async getArticleTags(id) {
      this.tagList = []
      const res = await this.$API.tag.getArticleTags(id)
      // 如果不存在权限就将权限列表清空
      if (!res.data) return (this.tagList = [])
      if (res.status == 200) {
        this.tagList = res.data
      }
    },
    // 多选项切换时
    handleSelectionChange(selection) {
      this.selectedArticles = selection
    },
    // 批量删除
    handleBatchDelete() {
      if (this.selectedArticles.length === 0) {
        this.$message.warning('请选择要删除的文章')
        return
      }

      this.$confirm('此操作将永久删除选中的文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const articleIds = this.selectedArticles.map(article => article.id)
          const formData = new FormData()
          formData.append('article_ids', articleIds.join(','))
          const res = await this.$API.article.BatchDeleteArticle(formData)
          if (res.status === 200) {
            this.$message.success('批量删除成功')
            this.getArticleList()
            this.content = ''
            this.selectedArticles = []
          } else {
            this.$message.error('批量删除失败')
          }
        })
        .catch(() => {
          this.$message.info('已取消批量删除')
        })
    }
  }
}
</script>
<style scoped>
.ArticleManage-container {
  width: 100%;
  padding: 20px;
}
.ArticleManage-options {
  margin-bottom: 20px;
}
.ArticleManage-table {
  width: 100%;
  margin: 10px auto;
}
</style>